//
//  MZNewsViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 17/04/12.
//  Copyright 2012 Mehfile Zainab. All rights reserved.
//

#import "MZNewsViewController.h"
#import "MZNewsDetailViewController.h"
#import "MZNewsDetailSelectableViewController.h"
#import "UIImage+Scale.h"
#import "MZNews.h"
#import "NewsXMLParser.h"
#import "FileManager.h"
#import "MZInfosViewController.h"
#import "MZNewsTableCell.h"

const double MZNewsCacheInterval = 10.0;

@implementation MZNewsViewController

@synthesize newsArray;
@synthesize spinner;
@synthesize alertView;

@synthesize dataPath;
@synthesize urlArray;
@synthesize filePath;
@synthesize fileDate;
@synthesize connection;
@synthesize XMLParsed;
@synthesize alertDisplayed;
//@synthesize refresh;

/*
- (void)showInfo:(id)sender
{
    NSLog(@"Info button tapped, show modal view");
    MZInfosViewController *mzInfosViewController = [[MZInfosViewController alloc]
                                                    initWithNibName:@"MZInfosViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mzInfosViewController];
    mzInfosViewController.title = @"Informations";
    [mzInfosViewController release];
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
									  initWithTitle:@"Fermer"
									  style:UIBarButtonItemStyleBordered
									  target:mzInfosViewController
									  action:@selector(GoBack:)];
	mzInfosViewController.navigationItem.leftBarButtonItem = barButtonItem;
    [self.tabBarController presentModalViewController:navController animated:YES];
    [navController release];
    
}
*/

-(IBAction)GoBack:(id)sender
{
	//[self dismissModalViewControllerAnimated:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)parseXMLFile {
    
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    //NSURL *url = [[NSURL alloc] initWithString:@"http://sitara.azad.free.fr/iosmehfile/remotetest/mzupdate.xml"];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:
                              [[NSData alloc] initWithContentsOfFile:[FileManager getCachedDataFile]]];
    
    //NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    
    //Initialize the delegate.
    //NewsXMLParser *parser = [[NewsXMLParser alloc] initXMLParser];
    NewsXMLParser *parser = [[NewsXMLParser alloc] initXMLParser:self];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors when parsing XML file");
    else
        NSLog(@"Error when parsing XML file!");
    
    //[self stopLoading];
    
    //[pool drain];
    
}

-(void) startLoading:(id)data  {
	
	//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[spinner setCenter:CGPointMake(140, 100)]; 
	
	NSString* messageTitleToUser = @"Mehfile Zainab"; 
	alertView = 
    [[UIAlertView alloc]	initWithTitle:messageTitleToUser 
                               message:@"Chargement..." 
                              delegate:self 
                     cancelButtonTitle:nil
                     otherButtonTitles:nil];
	
	[alertView addSubview:spinner];
	[spinner startAnimating];
	[alertView show]; 
	
	//[pool drain];
	
}

/*
-(void) stopLoading  {
	//if you programmatically want to close the alert view 
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	// stop spinner 
	[spinner stopAnimating];
    
    [self.tableView reloadData];
    
}
*/

- (void) initCache
{
    //NSLog(@"Prepare to use our own on-disk cache");
    
	/* create path to cache directory inside the application's Documents directory */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MZCache"];
    
	//NSLog(@"Initializing cache, value of dataPath : %@",self.dataPath);
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
    
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
								   withIntermediateDirectories:NO
													attributes:nil
														 error:&error]) {
		NSLog(@"Error when creating on-disk cache directory : %@",error);
		return;
	}
}

- (void) getFileModificationDate
{
    
    //NSLog(@"Check the last modified date of the data to see if we need to load a new version");
    
	/* default date if file doesn't exist (not an error) */
	self.fileDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		/* retrieve file attributes */
		NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
		if (attributes != nil) {
			self.fileDate = [attributes fileModificationDate];
		}
		else {
            NSLog(@"Error while checking file attribute of : %@ [ %@ ]",filePath,error);
		}
	}
}

-(void)endLoading {
        
    //XMLParsed = TRUE;
        
    [self parseXMLFile];
    
    // According to the mode, we :
    // - either close the loading popup window
    // - or end the refresh during Pull Down
    if (alertDisplayed) {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    } else {
        [refresh endRefreshing];
    }
        
    [self.tableView reloadData];
    
}

- (void) loadDataWithURL:(NSURL *)theURL
{
    
    //NSLog(@"Load new or existing cached data");
    
	[filePath release]; /* release previous instance */
	NSString *fileName = [[theURL path] lastPathComponent];
	filePath = [[dataPath stringByAppendingPathComponent:fileName] retain];
    NSLog(@"Get the path to the cached data : %@",filePath);
    
    
    [self getFileModificationDate];
    // get the elapsed time since last file update
    NSTimeInterval time = fabs([fileDate timeIntervalSinceNow]);
    if (time > MZNewsCacheInterval) {
        // file doesn't exist or hasn't been updated for at least one day
        self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
    }
    else {
        NSLog(@"Previously cached data found in cache and updated in last %f seconds.",MZNewsCacheInterval);
        [self endLoading];
    }
    
    //self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
    
}

-(void)doBackgroundWork {
    
    //NSLog(@"Background work in progress...");
    
    /* By default, the Cocoa URL loading system uses a small shared memory cache.
	 We don't need this cache, so we set it to zero when the application launches. */
    
    //NSLog(@"Turn off the NSURLCache shared cache");
    
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache release];
    
	[self initCache];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MZCache" ofType:@"plist"];
    if (path) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
        self.urlArray = [NSMutableArray array];
        for (NSString *element in array) {
            [self.urlArray addObject:[NSURL URLWithString:element]];
        }
        [array release];
    }
    //NSLog(@"Get the URL information from property list : %@",[self.urlArray objectAtIndex:0]);
    
	[self loadDataWithURL:[urlArray objectAtIndex:0]];
    
    //NSLog(@"Background work ended");
    
}

- (void)initNews {
	
	// We don't display the loading popup window if Pull Down refresh
    if (alertDisplayed) {
        [self startLoading:nil];
    }
    
    [self doBackgroundWork];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"news_icon"];
    }
    return self;
}

#pragma mark -
#pragma mark View lifecycle

-(void)refreshView {
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Actualisation en cours..."];
    
    // We set flag to indicate that we trigerred the Pull Down refresh
    alertDisplayed = FALSE;
    // We refresh the data
    [self initNews];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d MMM h:mm a"];
    NSString *lastUpdated = [NSString stringWithFormat:@"Dernière actualisation : %@", [formatter stringFromDate:[NSDate date]]];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
    //[refresh endRefreshing];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self enablePullDownRefreshToTarget:self action:@selector(refreshView) title:@"Actualiser"];
    
    /*
    refresh = [[UIRefreshControl alloc] init];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Actualiser"];
    [refresh addTarget:self
                   action:@selector(refreshView)
         forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    */
    
    // We set flag to indicate that the loading popup window should be displayed
    alertDisplayed = TRUE;
    // We refresh the data
	[self initNews];
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	NSLog(@"Number of news to display : %d",[newsArray count]);
    return [newsArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	return 88.0f;
	
}

// Set the cell transparent for iOS7 (default white background since iOS7)
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBackgroundColor:[UIColor clearColor]];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //static NSString *CellIdentifier = @"Cell";
    /*
     Set to nil because when scrolling table view,
     the label is created at each time, and is overwriting the previous label.
     */
    static NSString *CellIdentifier = nil;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //MZNewsTableCell *cell = (MZNewsTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        //NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MZNewsTableCell" owner:self options:nil];
        //cell = [nib objectAtIndex:0];
    }
    
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
    // Configure the cell...
    
    /*
	cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
	[cell.textLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsTitle]];
    */
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94.0, 1.0, 180.0, 34.0)];
    nameLabel.lineBreakMode = NSLineBreakByWordWrapping | NSLineBreakByTruncatingTail;
    nameLabel.numberOfLines = 2;
    [nameLabel setBackgroundColor:[UIColor clearColor]];
    [nameLabel setFont:[UIFont boldSystemFontOfSize:14.0]];
    [nameLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsTitle]];
    [cell.contentView addSubview:nameLabel];
    [nameLabel release];
    
    /*
    cell.titelLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.titelLabel.numberOfLines = 0;
	[cell.titelLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsTitle]];
    */
    
    /*
    MZNews *currentNews = [newsArray objectAtIndex:indexPath.row];
    cell.contentLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.contentLabel.numberOfLines = 2;
    [cell.contentLabel setText:currentNews.mzNewsContent];
    */
    
    MZNews *currentNews = [newsArray objectAtIndex:indexPath.row];
    currentNews.cellIndexPath = indexPath;
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(94.0, 36.0, 180.0, 30.0)];
    contentLabel.lineBreakMode = NSLineBreakByWordWrapping | NSLineBreakByTruncatingTail;
    contentLabel.numberOfLines = 2;
    [contentLabel setBackgroundColor:[UIColor clearColor]];
    [contentLabel setFont:[UIFont systemFontOfSize:13.0]];
    [contentLabel setText:currentNews.mzNewsContent];
    [cell.contentView addSubview:contentLabel];
    [contentLabel release];
    
    //[cell.detailTextLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsDate]];
    //[cell.dateLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsDate]];
    
    UILabel *dateNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94.0, 70.0, 180.0, 14.0)];
    [dateNameLabel setBackgroundColor:[UIColor clearColor]];
    [dateNameLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
    //[dateNameLabel setFont:[UIFont systemFontOfSize:12.0]];
    [dateNameLabel setTextColor:[UIColor grayColor]];
    [dateNameLabel setText:[[newsArray objectAtIndex:indexPath.row] getNewsDate]];
    [cell.contentView addSubview:dateNameLabel];
    [dateNameLabel release];
    
    //NSURL *url = [NSURL URLWithString:[[newsArray objectAtIndex:indexPath.row] getNewsImage]];
    //NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *urlString = [[newsArray objectAtIndex:indexPath.row] getNewsImage];
    NSString *imageFilePath = [FileManager getCachedDataFile:urlString];
    NSData *data = [NSData dataWithContentsOfFile:imageFilePath];
    
    //cell.imageView.frame = CGRectMake( 0, 0, 92, 88 );
    [cell.imageView setImage:[[UIImage imageWithData:data] scaleToSize:CGSizeMake(76.0f,72.0f)]];
    //[cell.thumbnailImageView setImage:[[UIImage imageWithData:data] scaleToSize:CGSizeMake(92.0f,88.0f)]];
    
	//[cell.imageView setImage:[[UIImage imageNamed:[[newsArray objectAtIndex:indexPath.row] getNewsImage]] scaleToSize:CGSizeMake(92.0f,88.0f)]];

    return cell;
	
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)showDetailView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
	MZNewsDetailSelectableViewController *detailViewController = [[MZNewsDetailSelectableViewController alloc] initWithNibName:@"MZNewsDetailSelectableViewController" bundle:nil];
	detailViewController.title = @"Mehfile Zainab";
	detailViewController.newsItem = [newsArray objectAtIndex:indexPath.row];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    detailViewController.navigationItem.rightBarButtonItem = barButtonItem;
    
	[self.navigationController pushViewController:detailViewController animated:YES];
    
	[detailViewController release];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self showDetailView:tableView atIndexPath:indexPath];
    
    /*
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	
	MZNewsDetailViewController *detailViewController = [[MZNewsDetailViewController alloc] initWithNibName:@"MZNewsDetailViewController" bundle:nil];
	detailViewController.title = @"Mehfile Zainab";
	detailViewController.newsItem = [newsArray objectAtIndex:indexPath.row];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    detailViewController.navigationItem.rightBarButtonItem = barButtonItem;
    
     // ...
     // Pass the selected object to the new view controller.
	[self.navigationController pushViewController:detailViewController animated:YES];
    
	[detailViewController release];
    */
    
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *) indexPath {
    
    [self showDetailView:tableView atIndexPath:indexPath];
    
    /*
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	
	MZNewsDetailViewController *detailViewController = [[MZNewsDetailViewController alloc] initWithNibName:@"MZNewsDetailViewController" bundle:nil];
	detailViewController.title = @"Mehfile Zainab";
	detailViewController.newsItem = [newsArray objectAtIndex:indexPath.row];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    detailViewController.navigationItem.rightBarButtonItem = barButtonItem;
    
    // ...
    // Pass the selected object to the new view controller.
	[self.navigationController pushViewController:detailViewController animated:YES];
    
	[detailViewController release];
	*/
    
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[newsArray release];
    [super dealloc];
}


/*
 ------------------------------------------------------------------------
 URLCacheConnectionDelegate protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark URLCacheConnectionDelegate methods

- (void) connectionDidFail:(URLCacheConnection *)theConnection
{
    NSLog(@"Connection failed!");
    [self endLoading];
    
    UIAlertView* errorAlertView = [[UIAlertView alloc] initWithTitle:@"Mehfile Zainab" message:@"Connexion impossible, merci de réessayer plus tard." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlertView show];
    
}


- (void) connectionDidFinish:(URLCacheConnection *)theConnection
{
    
    NSLog(@"Connection finished");
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES) {
        
        // apply the modified date policy
        /*
        [self getFileModificationDate];
        NSComparisonResult result = [theConnection.lastModified compare:fileDate];
        if (result == NSOrderedDescending) {
            // file is outdated, so remove it
            if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Error while removing item at path : %@ [ %@ ]",filePath,error);
            }
        }
        */
         
         NSLog(@"Clear cache because connection was successful");
         
         for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.dataPath error:&error]) {
             NSString *fileToDelete = [[self.dataPath stringByAppendingPathComponent:file] retain];
             NSLog(@"Delete file : %@",fileToDelete);
             BOOL success = [[NSFileManager defaultManager] removeItemAtPath:fileToDelete error:&error];
             if (!success || error) {
                 NSLog(@"Error when deleting data : %@",fileToDelete);
             }
         }
        
	}
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
		/* file doesn't exist, so create it */
		[[NSFileManager defaultManager] createFileAtPath:filePath
												contents:theConnection.receivedData
											  attributes:nil];
        
		NSLog(@"Newly cached data because data not found in cache or new data available : %@",filePath);
        
	}
	else {
		NSLog(@"Cached data is up to date, no new data available : %@",filePath);
	}
    
	/* reset the file's modification date to indicate that the URL has been checked */
    
	NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
	if (![[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:filePath error:&error]) {
		NSLog(@"Error while setting file attribute on : %@ [ %@ ]",filePath,error);
	}
	[dict release];
    
    [self endLoading];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //NSLog(@"Did end dragging");
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //NSLog(@"Did end decelerating");
}

@end

